<template>
	<view>
		<!-- <search-bar ref="search" :classifies='classifies'></search-bar> -->
		<view class="custom-pd-lr custom-mt">
			<!-- 	<swiper class="swiper-banner" circular indicator-color="#EBF9FC" indicator-active-color="#00B5DD"
				:indicator-dots="indicatorDots" :autoplay="autoplay" :interval="interval" :duration="duration">
				<swiper-item v-for="(item, index) in imgURL" :key="index">
					<image @click="bannerLink(item)" :src="listImgUrl + item.image + " class="custom-banner"
						mode="widthFix"></image>
				</swiper-item>
			</swiper> -->
			<swiper class="swiper-banner" circular indicator-color="#EBF9FC" indicator-active-color="#00B5DD"
					:indicator-dots="indicatorDots" :autoplay="autoplay" :interval="interval" :duration="duration">
					<swiper-item v-for="(item, index) in imgURL" :key="index">
						<image :src="item.image" class="custom-banner"
							mode="widthFix"></image>
					</swiper-item>
				</swiper> 
		</view>
		<view class="custom-bg-white" :class="{'st':true,'sticky-fixed':isF}">
			<uni-row :gutter="gutter" :width="nvueWidth">
				<view style="display: flex; flex-flow: row nowrap; justify-content: space-between;align-items: center;">
					<uni-col :span="22">
						<scroll-view id="tab-bar" class="scroll-h" :scroll-x="true" :show-scrollbar="false"
							:scroll-into-view="scrollInto">
							<view v-for="(tab,index) in tabBars" :key="tab.code" class="uni-tab-item" :id="`i${tab.code}`"
								:data-current="index" @click="ontabtap">
								<text class="uni-tab-item-title"
									:class="tabIndex==index ? 'uni-tab-item-title-active' : ''">{{tab.name}}</text>
							</view>
						</scroll-view>
					</uni-col>
				</view>
			</uni-row>
		</view>
		<view class="product-list custom-bg-white">
			<uni-row :gutter="20" style="display: block; width: 100%;">
				<uni-col :span="12">
					<view v-for="(item,index) in listRight" :key="index" class="product-item" @click="goTo(`../productDetails/productDetails?id=${item.id}`)">
						<view class="image">
							<!-- 图片字段：image → images，补充默认图 -->
							<image :src="item.images || '/static/image/default.png'" mode="widthFix"></image>
						</view>
						<view class="product-con">
							<!-- 简介字段：resume → detail -->
							<text class="label">{{item.detail}}</text>
							<!-- 标题字段：title → name -->
							<view class="title"><text>{{item.name}}</text></view>
							<view>
								<!-- 价格字段保留，补充小数格式化 -->
								<text class="price">¥{{item.price.toFixed(2)}}</text>
								<!-- 浏览次数：browseNum → viewNum -->
								<text class="see" v-if="item.viewNum">{{item.viewNum}}次浏览</text>
							</view>
							<!-- 商家名称：providerName → merchantName，补充默认值 -->
							<view class="vender">{{item.merchantName || '未知商家'}}</view>
						</view>
					</view>
				</uni-col>
				<uni-col :span="12" >
					<view v-for="(item,index) in listLeft" :key="index" class="product-item" @click="goTo(`../productDetails/productDetails?id=${item.id}`)">
						<view class="image" >
							<!-- 图片字段：image → images，补充默认图 -->
							<image :src="item.images || '/static/image/default.png'" mode="widthFix"></image>
						</view>
						<view class="product-con">
							<!-- 简介字段：resume → detail -->
							<text class="label">{{item.detail}}</text>
							<!-- 标题字段：title → name -->
							<view class="title"><text>{{item.name}}</text></view>
							<view>
								<!-- 价格字段保留，补充小数格式化 -->
								<text class="price">¥{{item.price.toFixed(2)}}</text>
								<!-- 浏览次数：browseNum → viewNum -->
								<text class="see" v-if="item.viewNum">{{item.viewNum}}次浏览</text>
							</view>
							<!-- 商家名称：providerName → merchantName，补充默认值 -->
							<view class="vender">{{item.merchantName || '未知商家'}}</view>
						</view>
					</view>
				</uni-col>
				
			</uni-row>
			<uni-load-more :status="LoadMore" v-if="showLoadMore" :content-text="contentText" ></uni-load-more>
		</view>
	</view>
</template>

<script>
	import {
		baseurl,
		queryDictDataTree,
		pageAppFarmProduce,
		queryAppAdList
	} from "@/api/user.js";
	let listImgUrl = "http://localhost:8080"
	export default {
		data() {
			return {
				classifies:['3'],
				imgURL:[{
						'image':'/static/image/1.png'
					},{
						'image':'/static/image/2.png'
					}],
				indicatorDots: true,
				autoplay: true,
				interval: 2000,
				duration: 500,
				tabIndex: 0,
				tabBars: [],
				scrollInto: "",
				gutter: 0,
				nvueWidth: 730,
				list: [],
				listLeft:[],
				listRight:[],
				page: 1,
				total: 0,
				stickyH: uni.upx2px(440),
				isF: false,
				currentIndex: "",
				listImgUrl,
				tempObj: {},
				showLoadMore: false,
				LoadMore: 'more',
				contentText: {
					contentdown: '...',
					contentrefresh: '加载中',
					contentnomore: '暂无更多数据'
				},
				timer:'',
			}
		},
		onPageScroll(e) {
			if (this.stickyH > e.scrollTop) {
				this.isF = false
			} else {
				this.isF = true
			}
		},
		onLoad() {
			console.log('load')
			queryDictDataTree({ 
				"dictType": "PRODUCE_TYPE", 
			}).then((data) => {
				this.tabBars = data.rows;
				console.log(this.tabBars)
			});
		},
		
		onShow() {
			this.nvueWidth = getApp().globalData.windowWidth;
			this.initData();
		},
		onUnload(){
			clearInterval(this.timer)
		},
		onPullDownRefresh() {
			console.log('onPullDownRefresh');
			this.initData();
			this.queryAppAdList([6])
		},
		onReachBottom() {
		  console.log("onReachBottom");
		  if (this.list.length >= this.total) {
		    this.LoadMore = 'no-more';
		    this.showLoadMore = true;
		    return
		  }
		  this.showLoadMore = true;
		  this.page++;
		  pageAppFarmProduce({
		    condition: {"produceType": this.tabBars[this.tabIndex]?.code || ''},
		    "page": this.page,
		    "pageSize": 10
		  }).then((res)=>{
		    if(res.success){ 
		      // 列表数据从 res.rows.list 改为 res.rows
		      let tempArr = res.rows; 
		      this.list = this.list.concat(tempArr);
		      tempArr.forEach((item,index)=>{
		        if(index % 2 != 0){
		          this.listLeft = this.listLeft.concat(item);
		        }else{
		          this.listRight = this.listRight.concat(item);
		        }
		      })
		      this.showLoadMore = false;
		    }
		  })
		},

		onHide(){
			console.log('hide')
		},
		onUnload(){
			console.log('Unload')
		},
		methods: {
			async pageAppFarmProduce(options) {
				const res = await pageAppFarmProduce(options);
				if(res.success){
					// 列表数据从 res.rows.list 改为 res.rows
					let tempArr = res.rows;
					tempArr.forEach((item,index)=>{
						if(index % 2 != 0){
							this.listRight.push(item);							
						}else{
							this.listLeft.push(item);
						}
					})
				}
				this.showLoadMore = false;
			},
			async queryDictDataTree(options) {
				const res = await queryDictDataTree(options)
				if (res.success) {
					this.tabBars = res.rows;
					
				} else {
					uni.showToast({
						title: '暂无数据！',
						icon: 'none'
					})
				}
			},
			async queryAppAdList(options) {
				const res = await queryAppAdList(options);
				let temp = res.rows
				if (res.success) {
					this.imgURL = res.rows[0].adProperties
				}
				
			},
			initData() {
			  this.page = 1;
			  this.list = [];
			  this.listLeft = [];
			  this.listRight = [];
			  this.showLoadMore = true;
			  this.LoadMore = 'loading';
			  console.log("tabs", this.tabIndex);
			  let options = {
			    condition: {"produceType": this.tabBars[this.tabIndex]?.code || ''},
			    page: this.page,
			    pageSize: 10
			  }
			  pageAppFarmProduce(options).then((res) => {
			    if(res.success){
			      // 列表数据从 res.rows.list 改为 res.rows
			      let tempArr = res.rows;
			      this.list = this.list.concat(tempArr);
			      // 总条数从 res.rows.total 改为 res.total
			      this.total = res.total;
			      this.listLeft = [];
			      this.listRight = [];
			      tempArr.forEach((item,index)=>{
			        if(index % 2 != 0){
			          this.listLeft.push(item);
			        }else{
			          this.listRight.push(item);
			        }
			      })
			      if(this.list.length >= this.total){
			        this.LoadMore = 'no-more';
			      }else{
			        this.showLoadMore = false;
			      }
			    }	
			  })
			  uni.stopPullDownRefresh();
			},

			
			bannerLink(e) {
				console.log("banner", e)
				if (e.forwordWay == 1) {
					if (e.forwordType == 1) {
						this.goTo(`../productDetails/productDetails?id=${e.forwordLink}`)
					}
					if (e.forwordType == 2) {
						this.goTo(`../agricultureService/serviceDetails/serviceDetails?id=${e.forwordLink}&sort=5`)
					}
					if (e.forwordType == 3) {
						let test = JSON.parse(e.extend)
						if (test.knowledgeCourseType == 1) {
							this.goTo(`../agricultureLecture/classDetails/classDetails?id=${e.forwordLink}`)
						}
						if (test.knowledgeCourseType == 2) {
							this.goTo(`../agricultureLecture/classDetails/video?id=${e.forwordLink}`)
						}
					}
					if (e.forwordType == 4) {
						if (e.forwordLink == 1 || e.forwordLink == 2) {
							console.log("bannerLink4")
							uni.switchTab({
								url: '/pages/agricultureLecture/agricultureLecture'
							})
						}
						if (e.forwordLink == 4 || e.forwordLink == 5) {
							uni.switchTab({
								url: '/pages/agricultureService/agricultureService'
							})
						}
						if (e.forwordLink == 3) {
							this.goTo('../moyangScent/moyangScent')
						}
						if (e.forwordLink == 6) {
							this.goTo('../loanService/loanService')
						}
						if (e.forwordLink == 7) {
							this.goTo('../subsidy/subsidy')
						}
						if (e.forwordLink == 8) {
							this.goTo('../beautyCity/beautyCity')
						}
					}
					if (e.forwordType == 5) {
						this.goTo(`../moyangProject/moyangProject?id=${e.forwordLink}`)
					}
				} else {
					this.outLink(e.forwordLink)
				}
			},
			toggle(type) {
				this.type = type
				// open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
				this.$refs.popup.open(type)
			},
			
			change() {

			},
			goTo(e) {
				var url = e;
				uni.navigateTo({
					url: url
				})
			},
			ontabtap(e) {
				console.log("tabe", e)
				this.scrollInto = e.currentTarget.id
				let index = e.target.dataset.current || e.currentTarget.dataset.current;
				this.switchTab(index);
				console.log("ontabtap");
			},
			ontabchange(e) {
				this.scrollInto = e.currentTarget.id
				let index = e.target.current || e.detail.current;
				this.switchTab(index);
			},
			bannerChange(e) {
				this.current = e.detail.current;
			},
			quickTabChange(code,index){
				this.scrollInto = 'i' + code;
				this.switchTab(index);
				this.$refs.popup.close()
			},
			switchTab(index) {
			  console.log("switchTab")
			  //let key = 'moyangtab_' + index
			  this.listLeft = [];
			  this.listRight = [];
			  this.scrollInto = 'i' + this.tabBars[index].code
			  // uni.getStorage({
			  //   key: key,
			  // }).then((data) => {
			  //   console.log('storage_tarerr', data);
			  //   if (data[1]) {
			  //     // 缓存数据列表从 data[1].data.list 改为 data[1].rows
			  //     let tempArr = data[1].rows;
			  //     tempArr.forEach((item,index)=>{
			  //       if(index % 2 != 0){
			  //         this.listLeft.push(item);
			  //       }else{
			  //         this.listRight.push(item);
			  //       }
			  //     })
			  //     // 当前页码从 data[1].data.page 改为 data[1].page
			  //     this.page = data[1].page;
			  //     // 总条数从 data[1].data.total 改为 data[1].total
			  //     this.total = data[1].total;
			  //     this.showLoadMore = true;
			  //     this.LoadMore = 'no-more';
			  //   } else {
				  console.log("发起请求。。");
			      this.page = 1;
			      let options = {
			        condition: {produceType:this.tabBars[index].id},
			        page: this.page,
					categoryId:this.tabBars[index].id,
			        pageSize: 10
			      }
				  console.log("发起分页请求，参数:",options)
			      this.showLoadMore = true;
			      this.LoadMore = 'loading'
			      pageAppFarmProduce(options).then((res) => {
			        if(res.success){
			          // 列表数据从 res.rows.list 改为 res.rows
			          let tempArr = res.rows;
			          tempArr.forEach((item,index)=>{
			            if(index % 2 != 0){
			              this.listLeft.push(item);
			            }else{
			              this.listRight.push(item);
			            }
			          })
			          // 总页数计算基于 res.total
			          this.maxpage = Math.ceil(res.total / 10);
			          // 缓存数据改为整个响应对象 res
			          uni.setStorage({
			            key: `moyangtab_${index}`,
			            data: res,
			            success: function() {
			              console.log('moyangtab_success');
			            }
			          });
			          this.LoadMore = 'no-more'
			        }
			      });
			    //}
			  //}).catch((data) => {})
			  this.tabIndex = index;
			},
		}
	}
</script>

<style lang="scss">
	page {
		width: 100%;
		background-image: url('https://staticfile-yj.obs.cn-north-4.myhuaweicloud.com/moyang-bg.png');
		background-repeat: no-repeat;
		background-size: 100% auto;
		background-color: linear-gradient(180deg, #0089D6 0%, rgba(0, 163, 214, 0.59) 55.21%, #FFFFFF 100%);
		height: 1000px;

		/* #ifdef MP */
		/* .test {
			position: absolute;
			bottom: 15px;
			right: 20rpx;
			display: block;
			width: 80rpx;
			height: auto;
		} */

		/* #endif */
	}

	.custom-weather {
		color: #ffffff;
		font-size: 40rpx;
		font-family: 'DIN';
		display: flex;
		align-items: center;
		flex-wrap: nowrap;

		image {
			width: 60rpx;
			margin-left: 6rpx;
			// margin-right: 30rpx;
		}
	}

	/* 搜索栏 */
	.search-bar /deep/ .uni-searchbar__box {
		justify-content: left !important;
	}

	.search-tips {
		padding: 2px 8px;
		height: 24px;
		line-height: 24px;
		background-color: #ffffff;
		border-radius: 20px;
		color: #505863;
		font-size: 24rpx;
		margin-left: 24rpx;
	}


	/* banner1 */
	.swiper-banner {
		max-height: 300rpx;
		border-radius: 12px;
	}

	.custom-banner {
		width: 100%;
		//height: auto;
		border-radius: 12px;
	}

	/* list-tab */
	.product {
		border-radius: 16px 16px 0 0;
		padding: 30rpx 0;
		background-image: linear-gradient(180deg, #FFFFFF 0%, #F5F8FB 100%);
		;
	}

	.swiper-box {
		display: flex;
		flex: 1;
		height: 1000px;
	}

	.swiper-item {
		display: flex;
		flex: 1;
		flex-direction: row;
	}

	.scroll-h {
		background-color: #ffffff;
		width: 100%;
		height: 80rpx;
		display: flex;
		flex-direction: row;
		white-space: nowrap;
	}

	.uni-tab-item {
		display: inline-block;
		flex-wrap: nowrap;
		padding-left: 34rpx;
		padding-right: 34rpx;
	}

	.uni-tab-item-title {
		color: #646A74;
		font-size: 28rpx;
		height: 72rpx;
		line-height: 72rpx;
		flex-wrap: nowrap;
		white-space: nowrap;
	}

	.uni-tab-item-title-active {
		display: inline-block;
		font-size: 32rpx;
		font-weight: bold;
		color: #283241;
		line-height: 72rpx;
		height: 72rpx;
		border-bottom: 3px solid #00C3CF;
	}

	.sticky-fixed {
		/* #ifndef H5 */
		position: fixed;
		top: 0;
		/* #endif */
		z-index: 999;
		left: 0;
		right: 0;
	}
</style>